import GCDWebServers

public enum MethodType {
    case post
    case get
}

public class SwiftDTApi: NSObject, GCDWebServerDelegate {
    /// 包名称
    let packageName = "SwiftDTApi"
    
    /// GCDWS
    public let webServer = GCDWebServer()
    
    public override init() {
        super.init()
        webServer.delegate = self
    }
    
    /// 添加接口
    public func add(_ path: String, method: MethodType = .get, responseHeader: [String: String] = [:] ,complation: @escaping (_ dtapiRequest: DTApiRequest) -> DTApiResponse) {
        // 请求方式
        var forMethod = "GET"
        var requestClass = GCDWebServerRequest.self
        if method == .post {
            forMethod = "POST"
            requestClass = GCDWebServerDataRequest.self
        }
        
        webServer.addHandler(forMethod: forMethod, path: path, request: requestClass) {(request, completionHandler) in
            // 返回参数
            var requestParams:[String: Any] = [:]
            if let dataRequest = request as? GCDWebServerDataRequest {
                // 将参数伪装成一个 url
                let data = "/?" + (String(data: dataRequest.data, encoding: .utf8) ?? "")
                requestParams = URL(string: data)?.getQueryParameters() ?? [:]
            } else {
                requestParams = request.url.getQueryParameters()
            }
            
            // 获取请求 headers
            let headers:[String: String] = request.headers
            
            // 完成返回
            let response = complation(DTApiRequest(params: requestParams, headers: headers))
            let dataResponse = GCDWebServerDataResponse(data: response.data, contentType: response.contentType)
            dataResponse.setValue("*", forAdditionalHeader: "Access-Control-Allow-Origin")
            dataResponse.setValue("GET,POST", forAdditionalHeader: "Access-Control-Allow-Methods")
            dataResponse.setValue("*", forAdditionalHeader: "Access-Control-Allow-Headers")

//            dataResponse.setValue(self.packageName, forAdditionalHeader: "Server")
//            for (key, value) in responseHeader {
//                dataResponse.setValue(value, forAdditionalHeader: key)
//            }
            
            completionHandler(dataResponse)
        }
    }
    
    /// 判断服务是否启动
    public func isRunning() -> Bool {
        return self.webServer.isRunning
    }
    
    /// 启动服务
    public func start(_ port: UInt = 8080) {
        if !isRunning() {
            do {
                try self.webServer.start(options: [
                    GCDWebServerOption_Port: port,
                    GCDWebServerOption_BonjourName: self.packageName
                ])
            } catch {
                print("Failed to start: \(error)")
            }
        }
    }
    
    /// 关闭服务
    public func stop() {
        if isRunning() {
            self.webServer.stop()
        }
    }
    
    /// 获取Web服务地址
    public func getServerURL() throws -> URL {
        if !isRunning() {
            throw NSError(domain: packageName, code: 0, userInfo: [NSLocalizedDescriptionKey: "Please start the service first!"])
        }
        
        if let serverURL = self.webServer.serverURL {
            return serverURL
        } else {
            throw NSError(domain: packageName, code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to obtain WebServer URL!"])
        }
    }
}
